from pathlib import Path
import sys
import subprocess
from shutil import which

try:
    from PIL import Image, ImageOps
    HAS_PIL = True
except Exception:
    HAS_PIL = False

target_dir = Path("/Users/yhd/Desktop/fuye/login/backgrounds/pc")
exts = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff"}
files = sorted([p for p in target_dir.iterdir() if p.is_file() and p.suffix.lower() in exts], key=lambda x: x.name.lower())

if not files:
    print("no eligible files found", file=sys.stderr)

has_cwebp = which("cwebp") is not None

def convert_with_pillow(src: Path, dst: Path) -> bool:
    try:
        with Image.open(src) as im:
            im = ImageOps.exif_transpose(im)
            if im.mode == "P":
                im = im.convert("RGBA")
            elif im.mode not in ("RGB", "RGBA"):
                im = im.convert("RGB")
            im.save(dst, "WEBP", quality=85, method=6)
        return True
    except Exception as e:
        print(f"pillow failed: {src.name}: {e}", file=sys.stderr)
        return False

def convert_with_cwebp(src: Path, dst: Path) -> bool:
    try:
        r = subprocess.run(["cwebp", "-q", "85", str(src), "-o", str(dst)], capture_output=True)
        if r.returncode != 0:
            print(f"cwebp failed: {src.name}: {r.stderr.decode('utf-8', 'ignore')}", file=sys.stderr)
            return False
        return True
    except Exception as e:
        print(f"cwebp error: {src.name}: {e}", file=sys.stderr)
        return False

def convert_with_sips(src: Path, dst: Path) -> bool:
    r = subprocess.run(["sips", "-s", "format", "webp", str(src), "--out", str(dst)], capture_output=True)
    if r.returncode != 0:
        print(f"sips failed: {src.name}: {r.stderr.decode('utf-8', 'ignore')}", file=sys.stderr)
        return False
    return True

i = 1
converted = 0
for p in files:
    out = target_dir / f"{i}.webp"
    ok = False
    if HAS_PIL:
        ok = convert_with_pillow(p, out)
    if not ok and has_cwebp:
        ok = convert_with_cwebp(p, out)
    if not ok:
        ok = convert_with_sips(p, out)
    if ok:
        print(f"{p.name} -> {out.name}")
        converted += 1
    else:
        print(f"failed to convert {p.name}", file=sys.stderr)
    i += 1

print(f"converted {converted} files to webp")